package com.mingke.java.Normal;

import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author mingke
 * @function 启动ServerSocket，处理客户端的请求
 * @date 2021/11/8
 * @desc IO阻塞+多线程，利用代码实现了BIO的网络模型，每个客户端都会分配一个线程来处理请求
 */
public class NormalSocketServer {
    public static long cidNum = 10;
    static int serverPort = 2021;

    public static void main(String[] args) {
        ServerSocket server = null;
        try {
            server = new ServerSocket(serverPort);
        }catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Server Socket has been start with port: "+serverPort);
        Socket socket = null;
        while(true) {
            try {
                //循环监听，处理客户端请求
                socket = server.accept();
                System.out.println("IP为："+socket.getInetAddress().getHostAddress()+" 的Socket Client连接到服务器");
            }catch (Exception e) {
                e.printStackTrace();
            }
            //创建新的线程来处理客户端的请求
            NormalSocketHandler socketHandler = new NormalSocketHandler(socket);
            //启动线程
            socketHandler.start();
        }
    }
}
